package com.yunyouyi.cpicture.infrastructure.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yunyouyi.cpicture.infrastructure.api.CosManager;
import com.yunyouyi.cpicture.infrastructure.config.CosClientConfig;
import com.yunyouyi.cpicture.infrastructure.exception.BusinessException;
import com.yunyouyi.cpicture.infrastructure.exception.ErrorCode;
import com.yunyouyi.cpicture.infrastructure.exception.ThrowUtils;
import com.yunyouyi.cpicture.infrastructure.manager.upload.model.dto.file.UploadPictureDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * @deprecated 改为使用upload包的模版方法
 */
@Service
@Slf4j
@Data
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;//客户端

    public UploadPictureDTO uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        //校验图片
        validPicture(multipartFile);
        //图片上传地址
        String UUID = RandomUtil.randomString(10);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFileName =String.format("%s_%s.%s", DateUtil.formatDate(new Date()), UUID, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s",uploadPathPrefix,uploadFileName);
        //解析结果并返回
        File file = null;
        try {
            file = File.createTempFile(uploadPath,null);
            multipartFile.transferTo(file);//前端传到本地临时文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = picWidth * 1.0 / picHeight;
            UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
            uploadPictureDTO.setUrl(cosClientConfig.getHost()+"/"+ uploadPath);
            getAVoid(uploadPictureDTO, originalFilename);
            uploadPictureDTO.setPicSize(multipartFile.getSize());
            uploadPictureDTO.setPicWidth(picWidth);
            uploadPictureDTO.setPicHeight(picHeight);
            uploadPictureDTO.setPicScale(picScale);
            uploadPictureDTO.setPicFormat(imageInfo.getFormat());
            return uploadPictureDTO;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败{}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            //临时文件清理
            deleteTempFile(file);
        }
    }

    private static void getAVoid(UploadPictureDTO uploadPictureDTO, String originalFilename) {
        uploadPictureDTO.setPicName(FileUtil.mainName(originalFilename));
    }

    public UploadPictureDTO uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        //校验图片
        validPicture(fileUrl);
        //图片上传地址
        String UUID = RandomUtil.randomString(10);
//        String originalFilename = fileUrl.getOriginalFilename();
        //获得文件名称
        String originalFilename = FileUtil.mainName(fileUrl);
        String uploadFileName =String.format("%s_%s.%s", DateUtil.formatDate(new Date()), UUID, FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("/%s/%s",uploadPathPrefix,uploadFileName);
        //解析结果并返回
        File file = null;
        try {
            file = File.createTempFile(uploadPath,null);
            //前端传到本地临时文件
//            originalFilename.transferTo(file);
            //下载文件
            HttpUtil.downloadFile(fileUrl,file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            //获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = picWidth * 1.0 / picHeight;
            UploadPictureDTO uploadPictureDTO = new UploadPictureDTO();
            uploadPictureDTO.setUrl(cosClientConfig.getHost()+"/"+ uploadPath);
            uploadPictureDTO.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureDTO.setPicSize(FileUtil.size(file));
            uploadPictureDTO.setPicWidth(picWidth);
            uploadPictureDTO.setPicHeight(picHeight);
            uploadPictureDTO.setPicScale(picScale);
            uploadPictureDTO.setPicFormat(imageInfo.getFormat());
            return uploadPictureDTO;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败{}", uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");
        }finally {
            //临时文件清理
            deleteTempFile(file);
        }
    }

    /**
     * 清理临时文件
     * @param file
     */
    private static void deleteTempFile(File file) {
        if(file != null){
            //删除临时文件
            boolean delete = file.delete();
            if(!delete){
                log.error("file delete error{}", file.getAbsolutePath());
            }
        }
    }

    /**
     * 校验文件
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        //限制文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 1024 * 1024 * 4, ErrorCode.PARAMS_ERROR,"文件大小不能超过4M");
        //判断后缀
        List<String> allowSuffixList = List.of("jpg", "jpeg", "png", "gif");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        log.info("文件后缀{}",fileSuffix);
        ThrowUtils.throwIf(!allowSuffixList.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"格式不支持");
    }
    /**
     * 校验url图片文件
     * @param fileUrl
     */
    public void validPicture(String fileUrl) {
        //校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl),ErrorCode.PARAMS_ERROR,"地址为空");
        //校验url格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址格式错误");
        }
        //检验url协议
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
                ErrorCode.PARAMS_ERROR,"文件地址协议错误");
        //发送head请求获取文件信息
        try(HttpResponse httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();/*//?*/){
            if (httpResponse.getStatus() != HttpStatus.SC_OK){
                return;
            }
            //进行文件校验
            String contentType = httpResponse.header("Content-Type");
            if(contentType != null){
                final List<String> ALLOW_CONTENT_TYPE = List.of("image/jpeg", "image/png", "image/gif","image/jpg");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPE.contains(contentType),ErrorCode.PARAMS_ERROR,"文件类型错误或不支持");
            }
            //文件大小
            String contentLength = httpResponse.header("Content-Length");
            if(contentLength != null){
                long fileSize = Long.parseLong(contentLength);
                ThrowUtils.throwIf(fileSize > 1024 * 1024 * 4,ErrorCode.PARAMS_ERROR,"文件大小不能超过4M");
            }
        }
    }
}
